var passwordRecoveryEnv = {
    // LIMITS and ERRORS defined in register.html.
    LIMITS: LIMITS,
    MESSAGES: MESSAGES,
    
    // errors global variable defined in register.html.
    server_validation_errors: errors,
    
    validator: null,
    
    // If page is currently in the middle of processing a form submit.
    busySubmitting: false
}


function createClientSideValidation() {
    var limits = passwordRecoveryEnv.LIMITS;
    var messages = passwordRecoveryEnv.MESSAGES;
    
    passwordRecoveryEnv.validator = $("#window form").validate({
        rules: {
            "email": {
                required:    limits["email_required"],
                rangelength: [limits["email_min_length"], limits["email_max_length"]],
                email:       true
            }
        },
        
        messages: {
            "email": {
                required:    messages["email_not_defined"],
                rangelength: messages["email_invalid_length"],
                email:       messages["email_invalid_format"]
            }
        },
        
        errorClass: "error"
    });
}


function showServerValidationErrorMessages(errors) {
    var messages = passwordRecoveryEnv.MESSAGES;
    var errorsToShow = { };
    
    if (errors["email_not_defined"])
        errorsToShow["email"] = messages["email_not_defined"];
    if (errors["email_invalid_length"])
        errorsToShow["email"] = messages["email_invalid_length"];
    if (errors["email_invalid_format"])
        errorsToShow["email"] = messages["email_invalid_format"];
    if (errors["user_not_found"])
        errorsToShow["email"] = "There is no user registered to this email.";
    
    passwordRecoveryEnv.validator.showErrors(errorsToShow);
}


function disableMultipleFormSubmission() {
    $("#window form").submit(function() {
        // We must check the form's validation, because submit event is
        // triggerred before validation. And so so we don't want to disable
        // submit button if the form is invalid, because the submission
        // will be cancelled anyway.
        if (passwordRecoveryEnv.validator.form()) {
            $(this).unbind("submit").submit(function() {
                return false;
            });
            
            $("#submit").val("Wait...");
        }
        else {
            return false;
        }
    });
}


$(document).ready(function() {
    createClientSideValidation();
    showServerValidationErrorMessages(passwordRecoveryEnv.server_validation_errors);
    disableMultipleFormSubmission();
})

